<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="mt15">
      <!-- 搜索和添加用户 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="searchUser"
            @input="searchUser"
          >
            <el-button
              @click="searchUser"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="14">
          <el-button type="primary" @click="addUserDia">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户表格 -->
      <el-table border class="mt15" :data="userList">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.mg_state"
                @change="setUserStatus(scope.row)"
              ></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div>
              <!--编辑用户 -->
              <el-button
                @click="editUserDia(scope.row)"
                type="primary"
                size="mini"
                icon="el-icon-edit"
              ></el-button>
              <!-- 删除用户 -->
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="deleteUserDia(scope.row.id)"
              ></el-button>
              <!-- 分配角色 -->
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setUserRoleDia(scope.row)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格分页 -->
      <!-- 
          分页参数说明：
          1.size-change:每页条数改变时，就会触发size-change
          2.current-change：当前页码改变时就触发
          3.current-page:当前页码
          4.page-sizes:每页显示条数的下拉选项
          5.page-size:当前每页显示的条数
          6.layout:分页布局选项 layout="total, sizes, prev, pager, next, jumper"
          7.total:分页的总条数
       -->
      <el-pagination
        class="mt15"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 6, 9, 12, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="isAddUserDia">
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserFormRules"
      >
        <el-form-item prop="username" label="用户名" label-width="80px">
          <el-input
            v-model="addUserForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password" label="密码" label-width="80px">
          <el-input
            v-model="addUserForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="mobile" label="手机号" label-width="80px">
          <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddUserDia = false">取 消</el-button>
        <el-button type="primary" @click="addUserOk">添加</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="isEditUserDia">
      <el-form
        ref="editUserFormRef"
        :model="addUserForm"
        :rules="addUserFormRules"
      >
        <el-form-item prop="username" label="用户名" label-width="80px">
          <el-input
            v-model="addUserForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="mobile" label="手机号" label-width="80px">
          <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditUserDia = false">取 消</el-button>
        <el-button type="primary" @click="editUserOk">编辑</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="isSetUserRoleDia"
      width="36%"
    >
      
      <div>
        <p>当前用户：<span>{{ currentUser.username }}</span></p>
        <p>当前角色：<span>{{ currentUser.role_name }}</span></p>
        <span class="mr10">分配新角色:---{{ currentRoleId }}</span>
          <el-select v-model="currentRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isSetUserRoleDia = false">取 消</el-button>
        <el-button type="primary" @click="setUserRoleOK"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUsersListAPI, addUserAPI, setUserStatusAPI } from "@/http/api";
import _ from "lodash";
export default {
  name: "users",
  data() {
    //验证邮箱方法
    const checkMail = (rule, value, callback) => {
      //邮箱正则
      const emailReg =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (!emailReg.test(value)) {
        return callback(new Error("您的邮箱规则不正确，请检查并重新输入"));
      }

      //满足验证规则，放行
      callback();
    };

    const checkMobile = (rule, value, callback) => {
      //手机正则
      const mobileReg = /^1[3456789]\d{9}$/;
      if (!mobileReg.test(value)) {
        return callback(new Error("您输入的手机号非法，请重新输入"));
      }
      //满足验证规则，放行
      callback();
    };

    return {
      //选择的新角色id
      currentRoleId:'',
      //角色列表
      rolesList:[],
      //是否显示分配角色对话框
      isSetUserRoleDia:false,
      //是不显示编辑对话框
      isEditUserDia: false,
      //添加用户验证规则
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", triggle: "blur" },
          {
            max: 10,
            min: 3,
            message: "请输入用户名的范围在3~~10之间",
            triggle: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户名", triggle: "blur" },
          {
            max: 16,
            min: 6,
            message: "请输入用户名的范围在3~~10之间",
            triggle: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", triggle: "blur" },
          { validator: checkMail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", triggle: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //添加/编辑共用用户表单对象
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //是否显示添加用户对话框
      isAddUserDia: false,
      value: true,
      //用户查询信息
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      //用户列表数据
      userList: [],
      //用户总条数
      total: 0,
      //当前用户id
      currentUserId: 0,
      //当前用户对象
      currentUser:{}
    };
  },
  created() {
    this.getUsersList(this.addUserForm);
  },
  methods: {
    //确认分配角色 
   async setUserRoleOK() {

      //调用分配角色接口
      const res=await this.$API.setUserRoleAPI(this.currentUserId,this.currentRoleId)
      console.log('分配新角色ok:',this.currentUserId,this.currentRoleId)

      //隐藏分配角色对话框
      this.isSetUserRoleDia=false

      //更新用户列表
      this.getUsersList()


    },
    //打开分配角色对话框
   async setUserRoleDia(row) {
      console.log('打开的用户信息：：：：',row)
      this.currentRoleId=''

      //解构获取用户名和角色名
      const {id,username,role_name}=row
      this.currentUserId=id
      //将用户名和角色名赋值给当前用户对象currentUser
      this.currentUser={username,role_name}

      //获取所有可能的角色列表接口
      const res=await this.$API.getRoleListAPI()
      console.log('返回角色列表：',res)
      this.rolesList=res;

      //隐藏分配角色对话框
      this.isSetUserRoleDia=true
    },
    //删除用户
    async deleteUserDia(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        this.$message({
          type: error,
          message: "已取消删除",
        });
      });

      if (res === "confirm") {
        //调删除接口
        await this.$API.deleteUserAPI(id);
        //更新数据
        this.getUsersList();
      }
    },
    //确定编辑
    editUserOk() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return;

        //符合验证规则，则调编辑操更新用户信息
        const { email, mobile } = this.addUserForm;

        const res = await this.$API.editUserAPI(this.currentUserId, {
          email,
          mobile,
        });
        console.log("更新结果：", res);

        //隐匿对话框
        this.isEditUserDia = false;
        //更新用户列表
        this.getUsersList();
      });
    },
    //打开编辑对话框
    editUserDia(row) {
      console.log("当前用户信息：", row);
      this.currentUserId = row.id;
      const { username, email, mobile } = row;
      this.addUserForm = { username, email, mobile };
      this.isEditUserDia = true;
    },
    //改变用户状态
    async setUserStatus(row) {
      //调用改变状态接口
      const res = await setUserStatusAPI(row.id, row.mg_state);
      console.log("改变状态返回的结果：", res);
    },
    //确认添加用户到后台数据库
    addUserOk() {
      //验证表单是否符合规则
      this.$refs.addUserFormRef.validate(async (valid) => {
        //不满足就直接返回
        if (!valid) return;

        //满足则调用后台添加用户的接口，将新用户添加到后台
        const res = await addUserAPI(this.addUserForm);
        console.log("添加成功结果：", res);
        this.isAddUserDia = false;
        //刷新用户列表
        this.getUsersList();
      });
    },
    //添加用户对话框
    addUserDia() {
      this.addUserForm = {};
      this.isAddUserDia = true;
    },
    //搜索用户
    searchUser: _.debounce(function () {
      this.getUsersList();
    }, 300),
    //每页条数改变时，就会触发
    handleSizeChange(val) {
      console.log("handleSizeChange:", val);
      this.queryInfo.pagesize = val;
      //重新加载用户列表
      this.getUsersList();
    },
    //当前页码改变时就触发
    handleCurrentChange(val) {
      console.log("handleCurrentChange:", val);
      this.queryInfo.pagenum = val;
      //重新加载用户列表
      this.getUsersList();
    },
    async getUsersList() {
      const res = await getUsersListAPI(this.queryInfo);
      console.log("用户列表：", res);
      let { total, users } = res;
      this.userList = users;
      this.total = total;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-card {
  box-shadow: 0 2px 4px 0 rgb(0 0 0 / 10%);
}
</style>
